﻿#include "DispatcherThread.h"
#include<QHostAddress>
#include<QJsonDocument>
#include "DataBase/mysql.h"
#include "Beans/userinfobean.h"
#include "constant.h"
DispatcherThread::DispatcherThread(QObject *parent):
    QThread(parent)
{

     this->moveToThread(this);
}

DispatcherThread::~DispatcherThread()
{
    delete m_tcpSocket;
}

void DispatcherThread::setSocketDescriptor(qintptr sockFd)
{

    socketDescriptor = sockFd;
}

void DispatcherThread::readData()
{


    qDebug()<<currentThread()<<"read thread iD=="<<currentThreadId();
    Qt::HANDLE threadId = QThread::currentThreadId();
    QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));
//    threadIdStr="123456";
    //读取缓冲区数据
    QByteArray buffer = m_tcpSocket->readAll();
    QString msg = buffer;
//    qDebug()<<">>>>receive stringData:"<<msg;
    emit updateMsg( m_tcpSocket->peerAddress().toString()+ "_" + QString::number(m_tcpSocket->peerPort()),msg);

    QJsonObject jsonObject = QJsonDocument::fromJson(buffer).object();

    jsonObject.insert("socketDescriptor",socketDescriptor);//插入socketDescriptor字段
    //ip处理
    QString ip_raw=m_tcpSocket->peerAddress().toString();
    QStringList ip_subList=ip_raw.split(":");
    QString ip=ip_subList[3];
    jsonObject.insert("IP",ip);//插入ip字段
    //注册和登录不用发到ui，其它信息需要传输到ui
    emit updateMsg(jsonObject);
//    qDebug()<<">>>>receive jsonData:"<<jsonObject;
    if(jsonObject.contains("fcode"))
    {
        int fcode=jsonObject["fcode"].toInt();
        if(fcode==100)
        {
            //注册
            UserInfoBean userInfo;
            QJsonObject userInfoBeanObj=jsonObject["userInfoBean"].toObject();
            if(userInfoBeanObj.contains("UserID")){
                userInfo.UserID=userInfoBeanObj["UserID"].toString();
            }
            if(userInfoBeanObj.contains("UserName")){
                userInfo.UserName=userInfoBeanObj["UserName"].toString();
            }
            if(userInfoBeanObj.contains("UserPwd"))
            {
                userInfo.UserPwd=userInfoBeanObj["UserPwd"].toString();
            }
            if(userInfoBeanObj.contains("UserAge")){
                userInfo.UserAge=userInfoBeanObj["UserAge"].toString();
            }
            if(userInfoBeanObj.contains("UserSex")){
                userInfo.UserSex=userInfoBeanObj["UserSex"].toString();
            }
            userInfo.IsLogin="0";//首次注册设置未登录
            userInfo.CurrentIP=ip;
            QJsonObject RegistInfo;
            QString file=Constant::DataBasePath;

            MySql *mySql = new MySql(file,threadIdStr);
            if(mySql->Query(userInfoBeanObj["UserID"].toString()))
            {
                RegistInfo.insert("fcode",100);//功能码（100，平板端注册）
                RegistInfo.insert("icode",1);//信息码
                RegistInfo.insert("msg","已存在该用户，请更换用户名！");
            }else
            {
                if(mySql->MyInsert(userInfo))
                {
                    RegistInfo.insert("fcode",100);
                    RegistInfo.insert("icode",2);//信息码
                    RegistInfo.insert("msg","恭喜您注册成功！");
                }else
                {
                    RegistInfo.insert("fcode",100);
                    RegistInfo.insert("icode",3);//信息码
                    RegistInfo.insert("msg","注册失败！");
                }
            }
            delete  mySql;

            m_tcpSocket->write(QJsonDocument(RegistInfo).toJson());

        }else if(fcode ==101)
        {
            //登录
            qDebug()<<"fcode=101:"<<"p1";
            UserInfoBean userInfo;
            QJsonObject userInfoBeanObj=jsonObject["userInfoBean"].toObject();
            if(userInfoBeanObj.contains("UserID")){
                userInfo.UserID=userInfoBeanObj["UserID"].toString();
            }
            if(userInfoBeanObj.contains("UserPwd"))
            {
                userInfo.UserPwd=userInfoBeanObj["UserPwd"].toString();
            }
            QString file=Constant::DataBasePath;

            MySql *mySql = new MySql(file,threadIdStr);
            UserInfoBean dataUserInfoBean;
            QJsonObject RegistInfo;
            QJsonObject UserInfoBean;//创建用户信息对象，处理客户端未注册的情况，直接从服务端获取用户信息，将用户信息的姓名，性别和年龄传递到客户端

            if(mySql->MySelect(userInfo.UserID,dataUserInfoBean))
//            if(MySql::getInstance(file,threadIdStr)->MySelect(userInfo.UserID,dataUserInfoBean))
            {
                qDebug()<<"fcode=101:"<<"查询存在该用户";
                if(dataUserInfoBean.UserPwd==userInfo.UserPwd )
                {
                    qDebug()<<"fcode=101:"<<"密码一致";
                    //查询到的密码和客户端传递过来的密码匹配,并且该账户未登录，则
                    UserInfoBean.insert("UserID",dataUserInfoBean.UserID);
                    UserInfoBean.insert("UserPwd",dataUserInfoBean.UserPwd);
                    UserInfoBean.insert("UserName",dataUserInfoBean.UserName);
                    UserInfoBean.insert("UserSex",dataUserInfoBean.UserSex);
                    UserInfoBean.insert("UserAge",dataUserInfoBean.UserAge);
                    //注释掉这块是考虑重复登录问题
//                    if(dataUserInfoBean.IsLogin=="0"){
//                        qDebug()<<"fcode=101:"<<"该账户未登录";
//                        RegistInfo.insert("fcode",101);//功能码（101，平板端登录）
//                        RegistInfo.insert("icode",1);//信息码
//                        RegistInfo.insert("userInfoBean",UserInfoBean);
//                        dataUserInfoBean.IsLogin="1";
//                        mySql->MyUpdate(dataUserInfoBean);//更新登录状态
//                    }else
//                    {
//                        qDebug()<<"fcode=101:"<<"该账户已经登录";
//                        RegistInfo.insert("fcode",101);//功能码（101，平板端登录）
//                        RegistInfo.insert("icode",4);//信息码
//                        RegistInfo.insert("msg","该用户已被登录");

//                    }
                    RegistInfo.insert("fcode",101);//功能码（101，平板端登录）
                    RegistInfo.insert("icode",1);//信息码
                    RegistInfo.insert("userInfoBean",UserInfoBean);

                }else
                {
                    qDebug()<<"fcode=101:"<<"用户名和密码不匹配";
                    RegistInfo.insert("fcode",101);//功能码（101，平板端登录）
                    RegistInfo.insert("icode",2);//信息码
                    RegistInfo.insert("msg","用户名和密码不匹配");
                }

            }else
            {
                qDebug()<<"fcode=101:"<<"查询失败";
                RegistInfo.insert("fcode",101);
                RegistInfo.insert("icode",3);//信息码
                RegistInfo.insert("msg","查询失败！");
            }
            delete  mySql;

            m_tcpSocket->write(QJsonDocument(RegistInfo).toJson());

        }else if(fcode==104)
        {
            //退出登录，将该用户的登录状态置为0
            UserInfoBean userInfo;
            QJsonObject userInfoBeanObj=jsonObject["userInfoBean"].toObject();
            if(userInfoBeanObj.contains("UserID")){
                userInfo.UserID=userInfoBeanObj["UserID"].toString();
            }
            QString file=Constant::DataBasePath;
            MySql *mySql = new MySql(file,threadIdStr);
            UserInfoBean dataUserInfoBean;
            if(mySql->MySelect(userInfo.UserID,dataUserInfoBean))
            {
                if(dataUserInfoBean.IsLogin=="1"){
                    dataUserInfoBean.IsLogin="0";
                    mySql->MyUpdate(dataUserInfoBean);//更新登录状态
                }
            }
            delete  mySql;
        }
        else if(fcode==215){
            UserInfoBean userInfo;
            QJsonObject userInfoBeanObj=jsonObject["userInfoBean"].toObject();
            if(userInfoBeanObj.contains("UserID")){
                userInfo.UserID=userInfoBeanObj["UserID"].toString();
            }
            QJsonObject userDataBeanObj=jsonObject["ppgResults"].toObject();


        }
    }

    return;
}

void DispatcherThread::slotDisconnected()
{
    //发送断开连接到显示页面
    qDebug()<<currentThread();
    qDebug()<<QString(">>>>disconnect to: %1").arg(m_tcpSocket->peerAddress().toString());
    QJsonObject jsonObject;
    //ip处理
    QString ip_raw=m_tcpSocket->peerAddress().toString();
    QStringList ip_subList=ip_raw.split(":");
    QString ip=ip_subList[3];
    jsonObject.insert("IP",ip);//插入ip字段
    jsonObject.insert("slotDisconnected",0);
    emit updateMsg(jsonObject);
    exit(0);
    emit closeMe(this);
}

void DispatcherThread::writeData(int sptr, QJsonObject json)
{
    if(sptr == socketDescriptor)
    {
        qDebug()<<"###########"<<json<< addressIp<<"###########";
        QByteArray byte_array = QJsonDocument(json).toJson();
        m_tcpSocket->write(byte_array);
        qDebug()<<currentThread()<<"write thread";
    }
}

void DispatcherThread::run()
{
    qDebug()<<currentThread();
    m_tcpSocket = new QTcpSocket;
    m_tcpSocket->setSocketDescriptor((qintptr)socketDescriptor);
    connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(readData()));
    connect(m_tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
    setAddressIp(m_tcpSocket->peerAddress().toString());
    emit updateClient(addressIp);
    this->exec();
}

QString DispatcherThread::getAddressIp() const
{
    return addressIp;
}

void DispatcherThread::setAddressIp(const QString &value)
{
    addressIp = value;
}
